package training.project.app.service.impl;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import training.project.app.domain.Flight;
import training.project.app.domain.FlightClient;
import training.project.app.domain.UserAccount;
import training.project.app.repository.UserDao;
import training.project.app.service.FlightClientService;
import training.project.app.service.FlightService;
import training.project.app.service.UserService;

@Service
@Transactional
public class UserServiceImpl implements UserService
	{
		@Autowired
		private UserDao clientRepository;
		@Autowired
		private FlightService flightService;
		@Autowired
		private FlightClientService flightClientService;

		public void saveClient(UserAccount client)
			{
				clientRepository.save(client);
			}

		public void deleteClient(UserAccount client)
			{
				clientRepository.delete(client);
			}

		public void updateClient(UserAccount client)
			{
				clientRepository.update(client);
			}

		public List<UserAccount> getClients()
			{
				List<UserAccount> clients = clientRepository.findAll();
				return clients;
			}

		@Override
		public UserAccount getUserById(Integer id)
			{
				return clientRepository.findById(id);
			}

		@Override
		public void bookFlight(Flight flight, UserAccount client)
			{
			}

		@Override
		public List<FlightClient> getFlightClients(UserAccount client)
			{
				List<FlightClient> flights = flightClientService
						.getFlightClients(client.getUserId());
				return flights;
			}

		@Override
		public UserAccount loadUserDetailsByLogin(String login)
			{
				return clientRepository.findByLogin(login);
			}

		@Override
		public Boolean purchaseFlight(UserAccount user,
				FlightClient flightClient)
			{
				if (user.getMoney() >= flightClient.getPrice())
					{
						clientRepository.purchaseFlight(user, flightClient);
						flightService.increasePrice(flightClient.getFlight());
						flightClientService.purchaseFlight(flightClient);
						return true;
					}
				else
					return false;
			}
	}
